<search-bar>
  <material-input
    label="Search in page"
    text-color="var(--header-text)"
    label-color="var(--header-accent-text)"
    color="var(--header-accent-text)"
  ></material-input>
  <script>
    import { router } from '@riotjs/route';

    export default {
      onMounted(props, state) {
        const input = this.$('input');
        let value = '';
        const notify = () => {
          if (value !== input.value) {
            props.onSearch(input.value.toLowerCase());
          }
          value = input.value;
        };
        input.addEventListener('keyup', notify);
        router.on.value(() => {
          input.value = '';
          notify();
        });
        window.addEventListener('keydown', (e) => {
          // F3 or CTRL + F
          if (e.keyCode === 114 || (e.ctrlKey && e.keyCode === 70)) {
            // already focused, fallback to default behavior
            if (document.activeElement === input) {
              return true;
            } else {
              e.preventDefault();
              input.focus();
            }
          }
        });
      },
    };

    export function matchSearch(search, value) {
      return !search || (value && value.toLowerCase().indexOf(search) >= 0);
    }
  </script>
  <style>
    :host material-input {
      line-height: initial;
      min-width: 5em;
    }

    @media screen and (max-width: 400px) {
      :host material-input {
        display: none;
      }
    }
  </style>
</search-bar>
